package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.UserType;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.po.WxAttention;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgWeixinMessage;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.wechat.message.YgTemplateMessage;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.JsonUtils;
import com.ygqh.baby.utils.MailUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/admin/small")
public class SmallMessageController extends BaseController<Object, Long> {

    @Autowired
    private YgWeixinMessageService ygWeixinMessageService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private WxAttentionService wxAttentionService;
    @Autowired
    private WxSmallMessageService wxSmallMessageService;
    @Autowired
    private YgUserAuthsService ygUserAuthsService;
    @Autowired
    private MailUtil mailUtil;

    @RequestMapping("/findMessageList")
    @ResponseBody
    public Message findMessageList(String platformNo) {
        return Message.success(ygWeixinMessageService.findSmallMessageList(platformNo));
    }

    @RequestMapping("/sendMessage")
    @ResponseBody
    public Message sendMessage(@RequestParam String weixinMessage) {
        YgWeixinMessage message = JsonUtils.toObject(weixinMessage, YgWeixinMessage.class);
        if (StringUtils.isBlank(message.getPlatformNo())) {
            message.setPlatformNo(Constant.YIIGOO_PLATFORM_NO);
        }
        List<WxAttention> attentionList = getAllAttention(message.getUserName(), message.getCreateBy(),
                message.getCreateTime(), message.getPlatformNo(), message.getYgSeoId());
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < attentionList.size(); i++) {
            System.err.println(attentionList.get(i).getOpenId());
            WxAttention attention = attentionList.get(i);
            fixedThreadPool.execute(() -> {
                YgTemplateMessage tplMessage = new YgTemplateMessage(attention.getOpenId(), message.getTemplateId(), message.getTemplateTitle(), null,
                        attention.getEvent());
                tplMessage.pushHead("#323232", message.getFirstData());
                if (StringUtils.isNotBlank(message.getKeyword1Data())) {
                    tplMessage.pushItem("keyword1", "#c32234", message.getKeyword1Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword2Data())) {
                    tplMessage.pushItem("keyword2", "#c32234", message.getKeyword2Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword3Data())) {
                    tplMessage.pushItem("keyword3", "#c32234", message.getKeyword3Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword4Data())) {
                    tplMessage.pushItem("keyword4", "#c32234", message.getKeyword4Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword5Data())) {
                    tplMessage.pushItem("keyword5", "#c32234", message.getKeyword5Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword6Data())) {
                    tplMessage.pushItem("keyword6", "#c32234", message.getKeyword6Data());
                }
                if (StringUtils.isNotBlank(message.getKeyword7Data())) {
                    tplMessage.pushItem("keyword7", "#c32234", message.getKeyword7Data());
                }
                tplMessage.setEmphasisKeyword("keyword1.DATA");
                tplMessage.setPage(message.getLinkUrl());
                tplMessage.setPlatformNo(message.getPlatformNo());
                wxSmallMessageService.sendTmplMsg(tplMessage);
                wxAttentionService.updateUpdateTime(attention.getId());
            });
        }
        fixedThreadPool.shutdown();

        String text = "消息内容：" + JSON.toJSONString(message) + "。\n" +
                "发送用户数：" + attentionList.size();
        mailUtil.simpleSend("sunshuo@yiigoo.com", "运营后台发送小程序模板【" + message.getTemplateTitle() + "】", text);
        return Message.success(null);
    }

    /**
     * @param testUserName 测试人员手机号（已绑定）
     * @param userGroup    用户群体
     * @param startDate    限制开始时间
     * @return
     */
    private List<WxAttention> getAllAttention(String testUserName, String userGroup, Date startDate,
                                              String platformNo, Integer ygSeoId) {
        List<WxAttention> attentionList = new ArrayList<>();
        if (StringUtils.isNotBlank(testUserName)) {
            YgUser user = ygUserService.findByUserName(testUserName);
            String openId;
            if (Constant.YIIGOO_PLATFORM_NO.equals(platformNo)) {
                openId = user.getSmallOpenId();
            } else {
                openId = ygUserAuthsService.getOpenId(user.getId(), platformNo, AppType.Small);
            }
            if (StringUtils.isNotBlank(openId)) {
                WxAttention attention = wxAttentionService.findByOpenId(openId);
                if (attention != null) {
                    attentionList.add(attention);
                }
            }
        } else {
            attentionList.addAll(getAllAttention(userGroup, startDate, platformNo, ygSeoId));
        }
        System.out.println("可发送用户数---》" + attentionList.size());
        return attentionList;
    }

    private List<WxAttention> getAllAttention(String userGroup, Date startDate, String platformNo, Integer ygSeoId) {
        List<WxAttention> attentionList = null;
        startDate = startDate == null ? DateConvertUtils.addDay(new Date(), -7) : startDate;
        switch (userGroup) {
            case "vip":
                attentionList = wxAttentionService.findByUser(10, null, startDate, ygSeoId, platformNo);
                break;
            case "userAgent":
                attentionList = wxAttentionService.findByUser(null, UserType.UserAgent, startDate, ygSeoId, platformNo);
                break;
            case "newCustomer":
                attentionList = wxAttentionService.findByNewCustomer(startDate, ygSeoId, platformNo);
                break;
            /*
             * case "48hour":
             *
             * break;
             */
            case "allClick":
                attentionList = wxAttentionService.selectAllAttention(startDate, ygSeoId, platformNo);
                break;
            case "unRegister":
                attentionList = wxAttentionService.selectAttentionList(startDate, ygSeoId, platformNo);
                break;
            case "unOrder":
                attentionList = wxAttentionService.findAttentionListNoOrder(startDate, ygSeoId, platformNo);
                break;
            default:
                break;
        }
        return attentionList == null ? new ArrayList<>() : attentionList;
    }

    @RequestMapping("/getAllAttentionCount")
    @ResponseBody
    public Message getAllAttentionCount(@RequestParam String userGroup, Date startDate, @RequestParam(defaultValue = "140") Integer ygSeoId, String platformNo) {
        List<WxAttention> attentionList = getAllAttention(userGroup, startDate, StringUtils.isBlank(platformNo) ? Constant.YIIGOO_PLATFORM_NO : platformNo, ygSeoId);
        return Message.success(attentionList.size());
    }
}
